// i.d(t, { n: () => MpWebStore })
import { NotImplementedError } from "../exception/store.exception"
import Logger from "../utils/Logger"

import httpEnum from "../enum/http.enum"
import { RequestQueue } from "../utils/request.util"

const a = new Logger("MpWebStore")
export default class MpWebStore<T = any> {
  static cache: Record<string, any>
  queue: RequestQueue
  config: any
  constructor(e: { queue: RequestQueue; [key: string]: any }) {
    this.queue = e.queue
    this.config = e
  }
  getRequestOptions(e) {
    return { responseType: "json" }
  }
  getCachedResponse(e, t = httpEnum.GET) {
    if (t === httpEnum.GET && e in MpWebStore.cache) {
      a.info(`Loaded ${e} from cache`)
      return MpWebStore.cache[e] as T
    }
  }
  setCachedResponse(e: string, t: T) {
    MpWebStore.cache[e] = t
  }
  async request(e: any, t: string, i = {}) {
    const { baseUrl: n } = this.config
    const s = Object.assign(Object.assign({}, this.getRequestOptions(`${n}${t}`)), i)
    const r = this.getCachedResponse(t, e)
    if (r) return r
    const o = await this.queue.request(e, `${n}${t}`, s)
    o && this.setCachedResponse(t, o)
    return o as T
  }
  async read(): Promise<any> {
    throw new NotImplementedError()
  }
}
MpWebStore.cache = {}
